#include "StdAfx.h"
#include <PSDFCore/Label/Label.h>
#include <osg/Billboard>
#include <osg/AutoTransform>

Label::Label( const string& content, 
			  unsigned short size, 
			  float x, float y, float z, 
			  float r, float g, float b, 
			  osgText::Text::AlignmentType align)
{
	wstring contentW = stringToWString(content);

	_autoTrans = new osg::AutoTransform;
	_autoTrans->setNormal(Vec3(0, 0, 1));
	_autoTrans->setAutoScaleToScreen(true);
	_autoTrans->setAutoRotateMode(AutoTransform::ROTATE_TO_SCREEN);
	_autoTrans->setPosition(Vec3d(x, y, z));
	//_autoTrans->setPivotPoint(Vec3d(x, y, z));
	_autoTrans->getOrCreateStateSet()->setMode(GL_LIGHTING, StateAttribute::OFF);

	this->addChild(_autoTrans);

	_text = new osgText::Text;
	_text->setText(contentW.c_str());
	_text->setCharacterSize(size);
	_text->setPosition(Vec3(0, 0, 0));
	_text->setColor(Vec4(r, g, b, 1.0));
	_text->setAlignment(align);
	_text->setFont("font/simkai.ttf");

	Geode* geode = new Geode;
	geode->addDrawable(_text);
	_autoTrans->addChild(geode);
}

Label::Label( osgText::Text* text )
{
	_text = text;
	Geode* geode = new Geode;
	geode->addDrawable(_text);
	this->addChild(geode);
}

void Label::setImageMark( const string& imageFile )
{
	int size = _text->getCharacterHeight();

	osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
	osg::ref_ptr<osg::Image> image = osgDB::readImageFile(imageFile);
	if (!image)
	{
		return;
	}
	texture->setImage( image.get() );

	osg::ref_ptr<osg::Geometry> quad = osg::createTexturedQuadGeometry( Vec3(-size/2, -size/2, 0), Vec3(size, 0, 0), Vec3(0, size, 0) );
	osg::StateSet* ss = quad->getOrCreateStateSet();
	ss->setMode(GL_BLEND, StateAttribute::ON);
	ss->setTextureAttributeAndModes( 0, texture.get() );

	Geode* geode = new Geode;
	geode->addDrawable(quad);

	if (_autoTrans->getNumChildren() == 1)
	{
		_text->setPosition(Vec3(size, 0, 0));
	}
	else // _autoTrans->getNumChildren() == 2
	{
		_autoTrans->removeChild(1);
	}
	_autoTrans->addChild(geode);
	
}

void Label::setNodeMark( Node* node )
{

	MatrixTransform* trans = new MatrixTransform;
	BoundingSphere bound = node->getBound();
	Matrixd matTrans, matScale;
	matTrans.makeTranslate(-bound.center());
	int size = _text->getCharacterHeight();
	float ratio = 1.0 * size / bound.radius();
	matScale.makeScale(ratio, ratio, ratio);
	trans->setMatrix(matTrans * matScale);

	trans->addChild(node);

	if (_autoTrans->getNumChildren() == 1)
	{
		_text->setPosition(Vec3(size, 0, 0));
	}
	else // _autoTrans->getNumChildren() == 2
	{
		_autoTrans->removeChild(1);
	}
	_autoTrans->addChild(trans);
}
